<template>
  <ion-page>
    <ion-header :translucent="true">
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-back-button default-href="/home"></ion-back-button>
        </ion-buttons>
        <ion-title>机器二维码</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true" class="ion-padding">
      <div class="qrcode-container">
        <ion-card class="qrcode-card">
          <ion-card-header>
            <ion-card-title class="card-title">扫描二维码</ion-card-title>
            <ion-card-subtitle>房东管理系统访问码</ion-card-subtitle>
          </ion-card-header>
          
          <ion-card-content>
            <div class="qrcode-display">
              <div v-if="loading" class="loading-state">
                <ion-spinner name="crescent" color="primary"></ion-spinner>
                <p>生成中...</p>
              </div>
              
              <div v-else-if="qrCodeDataURL" class="qrcode-wrapper">
                <img :src="qrCodeDataURL" alt="二维码" class="qrcode-image" />
                <div class="qrcode-info">
                  <p class="qrcode-id">二维码ID: LD-{{ landlordId }}-{{ timestamp }}</p>
                  <p class="qrcode-desc">使用手机扫描上方二维码访问房东管理系统</p>
                </div>
              </div>
              
              <div v-else class="error-state">
                <ion-icon :icon="alertCircleOutline" color="danger" size="large"></ion-icon>
                <p>二维码生成失败</p>
                <ion-button @click="generateQRCode" fill="outline" color="primary">
                  重新生成
                </ion-button>
              </div>
            </div>
          </ion-card-content>
        </ion-card>

        <div class="action-buttons">
          <ion-button expand="block" fill="outline" @click="refreshQRCode">
            <ion-icon :icon="refreshOutline" slot="start"></ion-icon>
            刷新二维码
          </ion-button>
          
          <ion-button expand="block" @click="saveQRCode" color="success">
            <ion-icon :icon="downloadOutline" slot="start"></ion-icon>
            保存到相册
          </ion-button>
        </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonButtons,
  IonBackButton,
  IonCard,
  IonCardHeader,
  IonCardTitle,
  IonCardSubtitle,
  IonCardContent,
  IonButton,
  IonIcon,
  IonSpinner,
  toastController
} from '@ionic/vue'
import {
  alertCircleOutline,
  refreshOutline,
  downloadOutline
} from 'ionicons/icons'
import { useUserStore } from '@/stores/user'
import QRCode from 'qrcode'

const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const qrCodeDataURL = ref('')
const landlordId = ref('')
const timestamp = ref('')

// 生成二维码
const generateQRCode = async () => {
  loading.value = true
  
  try {
    // 生成房东管理系统链接
    landlordId.value = userStore.user?.id?.toString() || '001'
    timestamp.value = Date.now().toString().slice(-6)
    const qrCodeUrl = `https://landlord.rentingsystem.com/manage?id=${landlordId.value}&token=${timestamp.value}`

    // 生成二维码图片
    qrCodeDataURL.value = await QRCode.toDataURL(qrCodeUrl, {
      width: 300,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    })
  } catch (error) {
    console.error('生成二维码失败:', error)
    qrCodeDataURL.value = ''
  } finally {
    loading.value = false
  }
}

// 刷新二维码
const refreshQRCode = async () => {
  await generateQRCode()
  
  const toast = await toastController.create({
    message: '二维码已刷新',
    duration: 1500,
    color: 'success',
    position: 'top'
  })
  await toast.present()
}

// 保存二维码
const saveQRCode = async () => {
  // 模拟保存功能
  const toast = await toastController.create({
    message: '二维码已保存到相册（模拟）',
    duration: 2000,
    color: 'success',
    position: 'top'
  })
  await toast.present()
}

// 页面加载时生成二维码
onMounted(() => {
  generateQRCode()
})
</script>

<style scoped>
.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100%;
  padding: 20px 0;
}

.qrcode-card {
  width: 100%;
  max-width: 400px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border-radius: 16px;
}

.card-title {
  text-align: center;
  color: var(--ion-color-dark);
  font-weight: 600;
}

.qrcode-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.loading-state,
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 40px 20px;
  color: var(--ion-color-medium);
}

.loading-state p,
.error-state p {
  margin: 0;
  font-size: 16px;
}

.qrcode-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.qrcode-image {
  width: 250px;
  height: 250px;
  border: 3px solid var(--ion-color-light);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.qrcode-info {
  text-align: center;
}

.qrcode-id {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--ion-color-medium);
  font-family: monospace;
}

.qrcode-desc {
  margin: 0;
  font-size: 14px;
  color: var(--ion-color-medium);
  line-height: 1.4;
}

.action-buttons {
  width: 100%;
  max-width: 400px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-buttons ion-button {
  --border-radius: 12px;
  height: 48px;
  font-weight: 500;
}
</style>
